package cn.tedu.sp02.item.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;

    //为了后面测试集群多台服务器，注入端口号
    @Value("${server.port}")
    private int port;

    @GetMapping("/{orderId}")
   public JsonResult<List<Item>> getItems(@PathVariable("orderId") String orderId) throws InterruptedException {
        log.info("orderId="+orderId+",port="+port);
        //添加随机延迟代码
        if (Math.random()<0.9){
            //随机产生0到5000随机延迟时长
            long t=new Random().nextInt(5000);
            log.info("延迟："+t);
            Thread.sleep(t);
        }
        List<Item> items=itemService.getItems(orderId);
        return JsonResult.ok().msg("port="+port).data(items);
    }
    //只处理post请求
    //@RequestBody  完整接收post请求协议体数据
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        itemService.decreaseNumbers(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }
}
